package monster.com.cvh.fragment;

import android.app.ProgressDialog;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.TbsListener;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.Permission;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import monster.com.cvh.R;
import monster.com.cvh.activity.FileDisplayActivity;
import monster.com.cvh.fragment.base.PermissionFragment;
import monster.com.cvh.util.MyConstant;
import monster.com.cvh.util.SPUtils;
import monster.com.cvh.view.RoundProgressBarWithProgress;
import okhttp3.Call;
import okhttp3.Response;

/**
 * @author: 13580
 * @data: 2018/4/12
 * @function:下载简历Fragment
 */
public class DownResumeFragment extends PermissionFragment {
    private static final String TAG = "DownResumeFragment";
    @BindView(R.id.round_progress_bar_fragment_down_resume)
    RoundProgressBarWithProgress mProgress;
    @BindView(R.id.iv_fragment_down_resume_loading)
    ImageView mIvLoading;
    @BindView(R.id.iv_fragment_down_resume_loaded)
    ImageView mIvLoaded;
    @BindView(R.id.tv_activity_down_resume_tips)
    TextView mTvTips;
    @BindView(R.id.tv_fragment_down_resume_done)
    TextView mTvDone;
    private AnimationDrawable mLoadingAnim;
    private String mDownStr;
    private ProgressDialog mDialog;
    private int mTemplateId;
    private String mFilePath;
    private TbsListener mTbsListener = new TbsListener() {
        @Override
        public void onDownloadFinish(int i) {
            Log.e(TAG, "tbs内核下载完成回调: " + i);
            //tbs内核下载完成回调
        }

        @Override
        public void onInstallFinish(int i) {
            Log.e(TAG, "内核安装完成回调: " + i);
            //内核安装完成回调
            if (mDialog != null && mDialog.isShowing()) {
                mDialog.dismiss();
                mDialog.cancel();
            }
            FileDisplayActivity.show(getContext(), mFilePath);
        }

        @Override
        public void onDownloadProgress(int progress) {
            Log.e(TAG, "下载进度监听: " + progress);
        }
    };
    private String mFileName;

    public static DownResumeFragment newInstance(int templateId, String fileName) {
        Bundle args = new Bundle();
        args.putInt(MyConstant.TEMPLATE_ID, templateId);
        args.putString(MyConstant.FILE_NAME, fileName);
        DownResumeFragment fragment = new DownResumeFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        if (args != null) {
            mTemplateId = args.getInt(MyConstant.TEMPLATE_ID);
            mFileName = args.getString(MyConstant.FILE_NAME);
        }
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_down_resume;
    }

    @Override
    protected void initData() {
        mDownStr = getResources().getString(R.string.activity_down_and_send_resume_downloading);
    }

    @Override
    protected void initEvent() {
        if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //SD卡已装入
            showToastLong("找不到SD卡");
            return;
        }
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "download" + File.separator
              +"CVLink" + File.separator;
        File file = new File(path);
        if (!file.exists()){
            file.mkdirs();
        }
        mLoadingAnim = (AnimationDrawable) mIvLoading.getBackground();
        mLoadingAnim.start();
        OkGo.<File>get(MyConstant.GET_RESUME_PDF)
                .tag(this)
                .params(MyConstant.TOKEN, SPUtils.getString(getContext(), MyConstant.TOKEN, ""))
                .params(MyConstant.TEMPLATE_ID, mTemplateId)
                .execute(new FileCallback(path,mFileName+System.currentTimeMillis()+ ".pdf") {
                    @Override
                    public void onSuccess(File file, Call call, Response response) {
                        if (!response.header("Content-Type").equals("application/pdf")){
                            mIvLoaded.setVisibility(View.VISIBLE);
                            mIvLoading.setVisibility(View.INVISIBLE);
                            mTvTips.setText(R.string.activity_down_and_send_resume_downloading_file_error);
                            file.delete();
                        }else {
                            mTvDone.setVisibility(View.VISIBLE);
                            mIvLoaded.setVisibility(View.VISIBLE);
                            mIvLoading.setVisibility(View.INVISIBLE);
                            mTvTips.setText(R.string.activity_down_and_send_resume_finished);
                            mProgress.setProgress(100);
                        }
                        if (mLoadingAnim != null && mLoadingAnim.isRunning()) {
                            mLoadingAnim.stop();
                        }
                        mFilePath = file.getAbsolutePath();
                    }

                    @Override
                    public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
                        super.downloadProgress(currentSize, totalSize, progress, networkSpeed);
                        int pro = (int) progress * 100;
                        mTvTips.setText(mDownStr + "(" + pro + "%)");
                        mProgress.setProgress(pro);

                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        mIvLoaded.setVisibility(View.VISIBLE);
                        mIvLoading.setVisibility(View.INVISIBLE);
                        mTvTips.setText(R.string.activity_down_and_send_resume_downloading_file_error);
                        showToastShort(R.string.activity_down_and_send_resume_downloading_file_error);
                    }
                });

        mDialog = new ProgressDialog(getContext());
        mDialog.setMessage(getResources().getString(R.string.fragment_user_reseume_download_init_pdf_plugin));
        mDialog.setCanceledOnTouchOutside(false);
    }

    @OnClick(R.id.tv_fragment_down_resume_done)
    public void onViewClicked() {
        requestPermission(new Action() {
            @Override
            public void onAction(Object data) {
                iniX5();
            }
        }, null, Permission.WRITE_EXTERNAL_STORAGE);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mLoadingAnim != null) {
            mLoadingAnim.stop();
            mLoadingAnim = null;
        }
        OkGo.getInstance().cancelTag(this);
    }

    private void iniX5() {
        if (QbSdk.canLoadX5(getContext())) {
            FileDisplayActivity.show(getContext(), mFilePath);
        } else {
            mDialog.show();
            QbSdk.initX5Environment(getContext(), new QbSdk.PreInitCallback() {
                @Override
                public void onCoreInitFinished() {
                }

                @Override
                public void onViewInitFinished(boolean b) {
                    if (b) {
                        if (mDialog != null && mDialog.isShowing()) {
                            mDialog.dismiss();
                            mDialog.cancel();
                        }
                        FileDisplayActivity.show(getContext(), mFilePath);
                    } else {
                        //tbs内核下载跟踪
                        QbSdk.setTbsListener(mTbsListener);
                    }
                }
            });
        }
    }
}
